package spring.cloud.tasks.executor.name_space.executor.task.task_listener.task_configuration;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.common.Service;
import spring.cloud.tasks.executor.name_space.executor.task.TaskExecutor;
import spring.cloud.tasks.executor.utils.LogUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 弹性化分布式任务配置服务.
 */
@Slf4j
@Setter
@Getter
public class TaskConfigurationService extends Service {
    // 参考http://stackoverflow.com/questions/17963969/java-regex-pattern-split-commna
    private static final String PATTERN = ",(?=(([^\"]*\"){2})*[^\"]*$)";

    public TaskConfigurationService(TaskExecutor taskExecutor) {
        super(taskExecutor);
    }

    /**
     * 获取任务分片总数.
     *
     * @return 任务分片总数
     */
    public int getTaskItemTotalCount() {
        return taskConfiguration.getTaskItemTotalCount();
    }

    public Map<Integer, String> getTaskItemIndexToTaskItemParameterMap() {
        Map<Integer, String> taskItemIndexToTaskItemParameterMap = new HashMap<>();
        String taskItemIndexAndTaskItemParametersString = taskConfiguration.getTaskItemIndexAndTaskItemParametersString();
        if (Strings.isNullOrEmpty(taskItemIndexAndTaskItemParametersString)) {
            return taskItemIndexToTaskItemParameterMap;
        }
        // 解释命令行参数
        Map<String, String> map = new HashMap<String, String>();
        JSONArray jsonArray = JSON.parseArray(taskItemIndexAndTaskItemParametersString);
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String taskItemIndexAndTaskItemParameter = jsonObject.toJSONString();
            String taskItemIndex = "";
            String taskItemParameter = "";
            int index = taskItemIndexAndTaskItemParameter.indexOf('=');
            if (index > -1) {
                taskItemIndex = taskItemIndexAndTaskItemParameter.substring(0, index).trim();
                taskItemParameter = taskItemIndexAndTaskItemParameter.substring(index + 1).trim();
            } else {
                throw new RuntimeException("Sharding item parameters '%s' format error" + taskItemIndexAndTaskItemParametersString);
            }
            map.put(taskItemIndex, taskItemParameter);
        }
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String taskItemIndex = next.getKey();
            String taskItemAndParameter = next.getValue();
            try {
                taskItemIndexToTaskItemParameterMap.put(Integer.valueOf(taskItemIndex), taskItemAndParameter);
            } catch (final NumberFormatException ex) {
                LogUtils.warn(log, "", "Sharding item key '%s' is invalid, it should be an integer, key '%s' will be dropped", taskItemIndex, taskItemIndex, ex);
            }
        }
        return taskItemIndexToTaskItemParameterMap;
    }

    /**
     * 获取任务自定义参数.
     *
     * @return 任务自定义参数
     */
    public String getPropertiesString() {
        return taskConfiguration.getPropertiesString();
    }


    /**
     * 获取超时时间
     *
     * @return 超时时间
     */
    public int getTimeoutMinutes() {
        return taskConfiguration.getTimeoutMinutes();
    }
    //


}
